package com.usian.wemedia.service.impl;

import com.alibaba.nacos.client.utils.JSONUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.exception.CatchCustomException;
import com.usian.common.exception.code.UserStatusCode;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.user.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmMaterialService;
import com.usian.wemedia.utils.KODOClientUtil;
import com.usian.wemedia.utils.OSSClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private FastDFSClient fastDFSClient;
    @Value("${fdfs.url}")//拼接路径
    private String fasturl;


    /**
     * 上传图片
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile, Integer status) {
        //检查参数
        if (multipartFile == null) {
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL, "文件为空");
        }
        String url = null;
        if (status == 5) {
            try {
                //2.上传图片到fasfdfs
                url = fastDFSClient.uploadFile(multipartFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (status == 2) {
            url = KODOClientUtil.saveImage(multipartFile);
        } else {
            OSSClientUtil ossClientUtil = new OSSClientUtil();
            url = ossClientUtil.saveImage(multipartFile);
        }

//保存数据库中
        WmUser user = WmThreadLocalUtils.getUser();
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(user.getId());
        wmMaterial.setUrl(url);
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setType((short) 0);//图片
        wmMaterial.setIsCollection((short) 0);//未收藏
        this.save(wmMaterial);
        wmMaterial.setUrl(fasturl + url);//合并路径返回给前端
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 素材列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        if (dto == null) {
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL, "对象为空");
        }
        //分页初始化
        dto.checkParam();
        //根据userid进行查询  收藏  时间倒叙
        //获取当前登录的用户
        Integer uid = WmThreadLocalUtils.getUser().getId();
        //带条件分页查询
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmMaterial::getUserId, uid);
        //是否收藏
        if (dto.getIsCollection() != null && dto.getIsCollection().shortValue() == 1) {
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        //按照日期倒序排序 相当于sql：order by isconllection desc,createtime desc
        lambdaQueryWrapper.orderByDesc(WmMaterial::getIsCollection, WmMaterial::getCreatedTime);
        IPage<WmMaterial> iPage = this.page(new Page<>(dto.getPage(), dto.getSize()), lambdaQueryWrapper);
        //返回结果
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) iPage.getTotal());
        List<WmMaterial> datas = iPage.getRecords();
        //用stream流的方式去拼接前缀
        datas = datas.stream().map(item -> {
            item.setUrl(fasturl + item.getUrl());
            return item;
        }).collect(Collectors.toList());
        responseResult.setData(datas);
        return responseResult;

    }

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 删除图片
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        if (id == null) {
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL, "删除的图片不能为空");
        }
        //检查图片是否被引用
        Integer count = wmNewsMaterialMapper.selectCount(new LambdaQueryWrapper<WmNewsMaterial>().eq(WmNewsMaterial::getMaterialId, id));
        if (count > 0) {
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL, "当前素材被引用不能删除");
        }
        WmMaterial wmMaterial = this.getById(id);
        if (wmMaterial == null) {
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL, "当前素材id有误，请检查");
        }
        if (!wmMaterial.getUserId().equals(WmThreadLocalUtils.getUser().getId())) {
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL, "当前用户信息有误");
        }
        //证明可以被删除
        this.removeById(id);
        //删除Fasrdfs上的图片
        fastDFSClient.delFile(wmMaterial.getUrl());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 公共的取消和收藏操作
     *
     * @param id
     * @param type
     * @return
     */
    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.检查参数
        if (id == null) {
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL, "Id不能为空");
        }
        // update set isconllection = type  where id= ? and userid= ?
        this.update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection, type).eq(WmMaterial::getId, id).eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId()));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


}
